package com.seeyon.groovy

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.seeyon.apps.cxgd.kit.HttpKit
import com.seeyon.apps.cxgd.kit.LogKit
import com.seeyon.apps.cxgd.kit.TCConfig
import com.seeyon.cap4.form.bean.FormDataMasterBean
import com.seeyon.cap4.form.bean.FormDataSubBean
import com.seeyon.cap4.form.bean.FormTableBean
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager
import com.seeyon.cap4.form.service.CAP4FormManager
import com.seeyon.ctp.common.AppContext
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem
import com.seeyon.ctp.organization.bo.V3xOrgDepartment
import com.seeyon.ctp.organization.bo.V3xOrgMember
import com.seeyon.ctp.organization.manager.OrgManager
import com.seeyon.dee.codelib.TcDateKit
import com.seeyon.dee.codelib.TcFormCap4Kit
import com.seeyon.dee.codelib.StrKitTC

import java.text.SimpleDateFormat


//出差申请商旅订票

def masterId = getParaByName(document,"masterId");
OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
EnumManager enumManager = AppContext.getBean("enumManagerNew");
CAP4FormManager cap4FormManager = (CAP4FormManager)AppContext.getBean("cap4FormManager");
CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager)AppContext.getBean("cap4FormDataManager");


FormDataMasterBean formDataMasterBean = cap4FormManager.getSessioMasterDataBean(masterId);
if(formDataMasterBean == null){
    printlnLog("修改出差申请商旅订票获取缓存formDataMasterBean为null，masterId："+masterId);
}
FormTableBean formTableBean = formDataMasterBean.getFormTable();
//获取表单上的数据
String oaNumber = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "流程编号"));
Date clCreate = TcFormCap4Kit.getFieldValue(formDataMasterBean, "填写日期");
/*差旅内容*/
String travelDescription = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "出差目的"));
String oaCreateMenberId = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "申请人"));
V3xOrgMember v3xOrgMember1 = orgManager.getMemberById(Long.parseLong(oaCreateMenberId));

//成本中心
String isyfxmcc = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "是否研发项目出差"));
CtpEnumItem ctpEnumItem = enumManager.getCtpEnumItem(Long.parseLong(isyfxmcc))

String yfxmName = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "研发项目名称"));
String yfxmCode = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "研发项目编码"));
String yskmName = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "预算科目"));
String yskmmCode = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "预算科目代码"));
String fybmId = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "费用承担部门"));
V3xOrgDepartment fybm = null
if(!fybmId.equals("")){
    fybm = orgManager.getDepartmentById(Long.parseLong(fybmId))
}
String sapCbzx = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "成本中心"));
String sapCbzxNumber = StrKitTC.str(TcFormCap4Kit.getFieldValue(formDataMasterBean, "OA预算成本中心代码"));

//明细表中的值
List<HashMap<String,Object>> itemList = new ArrayList<HashMap<String, Object>>();
List<HashMap<String,Object>> personList = new ArrayList<HashMap<String, Object>>();
List<HashMap<String,Object>> costCenterList = new ArrayList<HashMap<String, Object>>()
printlnLog("修改开始组装成本中心数据==========================================");
//成本中心数据组装
HashMap<String,Object> costCenterMap = new HashMap<String, Object>()
if(ctpEnumItem.getShowvalue().equals("是")){
    //成本中心名称
    costCenterMap.put("costCenterName",yfxmName+"_"+yskmName);
    //成本中心编码
    costCenterMap.put("costCenterCode",yfxmCode+"_"+yskmmCode);
    //成本中心类型名称
    costCenterMap.put("costCenterTypeName","研发类型出差");
    //成本中心类型编码
    costCenterMap.put("costCenterTypeCode","costCenter");
}else{
    //成本中心名称
    costCenterMap.put("costCenterName",fybm == null?"":fybm.getName()+"_"+sapCbzx);
    //成本中心编码
    costCenterMap.put("costCenterCode",fybm == null?"":fybm.getCode()+"_"+sapCbzxNumber);
    //成本中心类型名称
    costCenterMap.put("costCenterTypeName","部门项目出差");
    //成本中心类型编码
    costCenterMap.put("costCenterTypeCode","costCenter");
}
//是否默认值 成本中心统一类型仅一个值时默认传true
costCenterMap.put("isDefault",true);
costCenterList.add(costCenterMap);
printlnLog("修改组装成本中心数据组装结束，组装出差人信息==========================================");
List<FormDataSubBean> displayList = TcFormCap4Kit.getSubBeansByDisplay(formDataMasterBean, "出差明细");
for (FormDataSubBean display :displayList){
    HashMap<String,Object> perSonMap = new HashMap<String, Object>();
    HashMap<String,Object> itemMap = new HashMap<String, Object>()
    //差旅开始时间
    itemMap.put("startDate",TcDateKit.getDayBeforeSp((Date)TcFormCap4Kit.getSubFieldValue(display, "预计开始时间")));
    //差旅结束时间
    itemMap.put("endDate",TcDateKit.getDayBeforeSp((Date)TcFormCap4Kit.getSubFieldValue(display, "预计结束时间")));
    //差旅出发地
    String departCity = StrKitTC.str(TcFormCap4Kit.getSubFieldValue(display, "出发城市同程"));
    if(!departCity.equals("")){
        CtpEnumItem departCityEnum = enumManager.getCtpEnumItem(Long.parseLong(departCity))
        departCity = departCityEnum.getShowvalue();
    }
    itemMap.put("departCity",departCity);
    //差旅目的地
    String arriveCity = StrKitTC.str(TcFormCap4Kit.getSubFieldValue(display, "目的城市同程"));
    if(!arriveCity.equals("")){
        CtpEnumItem arriveCityEnum = enumManager.getCtpEnumItem(Long.parseLong(arriveCity))
        arriveCity = arriveCityEnum.getShowvalue();
    }
    itemMap.put("arriveCity",arriveCity);
    itemList.add(itemMap);


    String ciMemberId = StrKitTC.str(TcFormCap4Kit.getSubFieldValue(display, "出差人"))
    V3xOrgMember v3xOrgMember = orgManager.getMemberById(Long.parseLong(ciMemberId))
    //差旅人姓名
    perSonMap.put("name",v3xOrgMember.getName());
    //亲属关系
    perSonMap.put("relation",0);
    //人员类型
    perSonMap.put("passengerType",0);
    //外部员工ID
    perSonMap.put("outEmployeeId",v3xOrgMember.getId());
    personList.add(perSonMap);
}
printlnLog("修改出差人信息数据组装结束，开始预备接口参数==========================================");

//时间格式化
SimpleDateFormat sp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Map<String,Object> paramMap = new HashMap<String, Object>()
paramMap.put("outTravelApplyNo",oaNumber);    //外部差旅单号
paramMap.put("travelApplyType",1);      //差旅类型  1 普通发票   2福利差旅
paramMap.put("travelApplyTime",sp.format(new Date()));     //差旅申请时间   格式2019/11/26  8:35:38
paramMap.put("travelUpdateTime",sp.format(new Date()));    //差旅修改时间    格式2019/11/26  8:35:38
paramMap.put("operationType",1);        //操作类型 1：新增，2：更新； 注意数据类型
paramMap.put("outEmployeeId",v3xOrgMember1.getId());       //外部员工ID（申请人）test001
paramMap.put("travelDescription",travelDescription);   //差旅内容
paramMap.put("bookableProducts","1,2,3,4,5");    //可预订产品 可预订产品类型，逗号分隔。1：国内机票 ，2：国际机票 ，3：国内酒店 ，4：海外酒店 ，5：火车票 ，6：用车
paramMap.put("status",1);              //状态  1 通过 2 作废 ；注意数据类型
paramMap.put("itemList",itemList);
paramMap.put("personList",personList);
paramMap.put("costCenterList",costCenterList);



String accessToken = GetToken()
//组装请求数据
String random = UUID.randomUUID().toString();
String timestamp = new Date().getTime();
Map map = new HashMap<String, Object>();
map.put("accessToken",accessToken);
map.put("isEncrypt",false);
map.put("random",random);
map.put("timestamp",timestamp);
map.put("param",paramMap);

printlnLog("修改开始预备接口参数数据结束，开始推送==========================================");
//转json
String mapString = JSON.toJSONString(map);
printlnLog("修改出差申请推送同城订票申请发送cans参数："+mapString)
String md5 = StrKitTC.stringToMD5(mapString);
md5 = md5.toLowerCase();
//获取sgin
String secret =  TCConfig.getSecret();
String sign = StrKitTC.stringToMD5(md5 + secret);
sign = sign.toLowerCase();

//发送
String url = TCConfig.getWBCLDTB()+sign;
printlnLog("修改商旅订票发送接url："+url);
String data = HttpKit.post(url,new HashMap(),mapString)
LogKit.addLog(oaNumber, "推送同程差旅信息-更新", mapString, data);
printlnLog("修改商旅订票申请发送接口返回数据："+data);
JSONObject object = JSONObject.parseObject(data)
Boolean success = (Boolean) object.get("success")
if(object.containsKey("success")){
    if(success){
        def string = object.get("errorCode").toString()
        if(string.equals("0")){
            Map map1 = (Map<String, Object>) object.get("data");
            String travelApplyNo = map1.get("travelApplyNo").toString()
            CollBackFormData(cap4FormDataManager,formDataMasterBean,formTableBean,"出差单号",travelApplyNo)
        }else{
            def errstring = object.get("errorMessage").toString()
            setHighSetStr(document,'F','Y',"同程接口返回错误信息："+errstring,string);
        }
    }else{
        def string = object.get("errorMessage").toString()
        setHighSetStr(document,'F','Y',"同程接口返回错误信息："+string,'接口返回状态：'+success);
    }
}else{
    setHighSetStr(document,'F','Y',"同程接口返回错误信息："+data,'接口返回状态：'+success);
}



//获取token
private String GetToken(){
    String accessToken = "";
    String config = StrKitTC.getAccessToken(TCConfig.getAccount(), TCConfig.getPassword());
    try {
        String s = HttpKit.post(TCConfig.getUrl(),new HashMap(), config);
        JSONObject jsonObject = JSONObject.parseObject(s);
        Boolean success = (Boolean)jsonObject.get("success");
        if(success){
            Map<String,Object> data = (HashMap)jsonObject.get("data");
            accessToken = data.get("accessToken").toString();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return accessToken;
}



//回写表单数据
private void CollBackFormData(CAP4FormDataManager cap4FormDataManager,FormDataMasterBean formDataMasterBean,FormTableBean formTableBean,String disPlayName,String value){
    def display = formTableBean.getFieldBeanByDisplay(disPlayName);
    formDataMasterBean.addFieldValue(display.getName(),value);
//    cap4FormDataManager.insertOrUpdateMasterData(formDataMasterBean);
}

